package com.ls.bpmn.controller;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ls.common.*;
import com.ls.bpmn.entity.Category;
import com.ls.bpmn.service.ICategoryService;
import com.ls.common.shiro.ActiverUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private ICategoryService categoryService;


    // 获取所有流程分类
    @GetMapping("/list")
    public DataGridView list(PageModel pageModel, Integer parentId) {
        Page<Category> page = new Page<>(pageModel.getPage(), pageModel.getLimit());
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        if (parentId == null) {
            queryWrapper.eq("parent_id", 0);
        } else {
            queryWrapper.eq("parent_id", parentId);
        }
        Page<Category> resultPage = this.categoryService.page(page, queryWrapper);
        return new DataGridView(resultPage.getTotal(), resultPage.getRecords());
    }


    @PostMapping("/save")
    public ResultObj addCategory(@RequestBody Category category) {
        try {
            // 校验分类名称不能为空
            if (StrUtil.isBlank(category.getName())) {
                return new ResultObj(-1, "分类名称不能为空！");
            }
            // 校验类型必须为 "0" 或 "1"
            if (!"0".equals(category.getType()) && !"1".equals(category.getType())) {
                return new ResultObj(-1, "类型参数不合法！允许值：0（流程类型）或 1（分类）");
            }

            Subject subject = SecurityUtils.getSubject();
            ActiverUser activerUser = (ActiverUser) subject.getPrincipal();
            if (activerUser == null) {
                return ResultObj.LOGIN_ERROR;
            }
            String username = activerUser.getUser().getLoginname();

            if (ObjectUtil.isEmpty(category.getId())) {

                 // 新增操作
                category.setCreator(username);
                category.setCreateTime(LocalDateTime.now());
            } else {
                // 更新操作
                category.setModifier(username);
                category.setUpdateTime(LocalDateTime.now());
            }

            boolean success = categoryService.saveOrUpdate(category);
            return success ?
                    new ResultObj(200, "操作成功!") :
                    new ResultObj(-1, "操作失败!");

        } catch (Exception e) {
            return new ResultObj(-1, "操作异常: " + e.getMessage());
        }
    }

    // 删除流程分类
    @DeleteMapping("/delete/{id}")
    public ResultObj deleteCategory(@PathVariable Integer id) {
        // 检查是否存在子节点（可选，前端已做检查）
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        if (categoryService.count(queryWrapper) > 0) {
            return new ResultObj(-1, "存在子节点，无法删除！");
        }
        boolean success = categoryService.removeById(id);
        return success ? ResultObj.DELETE_SUCCESS : ResultObj.DELETE_ERROR;
    }

    //树形结构
    @GetMapping("/tree")
    public DataGridView tree() {
        List<Category> list = categoryService.list(new QueryWrapper<Category>().eq("type", 1));
        List<TreeNode> treeNodes = new ArrayList<>();
        for (Category category : list) {
            TreeNode node = new TreeNode(
                    category.getId(),
                    category.getParentId(),
                    category.getName(), // 确保此处字段对应前端的 title
                    false
            );
            treeNodes.add(node);
        }
        return new DataGridView(treeNodes); // DataGridView 的 data 字段直接包含列表
    }

    @RequestMapping("/checkCatHasChildrenNode")
    public Map<String, Boolean> checkCatHasChildrenNode(Integer id) {
        Map<String, Boolean> map = new HashMap<>();
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        List<Category> list = this.categoryService.list(queryWrapper);
        map.put("value", list.size() > 0);
        return map;
    }

}
